package com.baijiayun.liveuibase.utils;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Outline;
import android.graphics.drawable.BitmapDrawable;
import android.media.AudioManager;
import android.media.SoundPool;
import android.net.Uri;
import android.os.Build;
import androidx.core.content.FileProvider;

import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewOutlineProvider;
import android.view.inputmethod.InputMethodManager;

import com.baijiayun.livecore.models.LPSnippetPullResModel;
import com.baijiayun.livecore.models.file.homework.LPHomeworkModel;
import com.baijiayun.liveuibase.R;
import com.baijiayun.liveuibase.providers.HomeworkProvider;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class BaseUIUtils {
    public static void hideSoftInput(View view, Context context) {
        if (context != null) {
            InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
            if (imm != null && imm.isActive()) {
                imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
            }
        }
    }

    public static String getLastUserNumber(LPSnippetPullResModel snippetPullResModel) {
        if (snippetPullResModel.userParticipatedList.size() > 0) {
            return snippetPullResModel.userParticipatedList.get(snippetPullResModel.userParticipatedList.size() - 1).getNumber();
        }
        return "";
    }

    /**
     * 保存截图
     */
    public static void saveViewCapture(View view, String dir) {
        Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        view.draw(canvas);
        File f = new File(dir, "bjy_capture_" + System.currentTimeMillis() + ".png");
        try {
            FileOutputStream out = new FileOutputStream(f);
            bitmap.compress(Bitmap.CompressFormat.PNG, 80, out);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //24小时内有效
    public static String formatTime(int timeInSeconds) {
        if (timeInSeconds < 10) {
            return String.valueOf(timeInSeconds);
        } else if (timeInSeconds < 60) {
            return "00:" + timeInSeconds;
        } else if (timeInSeconds < 60 * 60) {
            return ((timeInSeconds / 60) < 10) ? "0" + timeInSeconds / 60 + ":" + timeInSeconds % 60 : timeInSeconds / 60 + ":" + timeInSeconds % 60;
        } else {
            return timeInSeconds / 3600 + ":" + timeInSeconds % 3600 / 60 + ":" + timeInSeconds % 3600 % 60;
        }
    }

    /**
     * 将 long 时间格式化 仅支持正数，负数会被转成正数，例：1200 -> 00:20:00，即20分钟
     * @param time 时间 - 秒级
     * @return "HH:mm:ss" 格式的字符串
     */
    public static String formatTimeByLong(long time) {
        time = Math.abs(time);
        long sec = time % 60;
        long min = time % (60 * 60) / 60;
        long hou = time / (60 * 60);
        return fillZeroToSize_2(hou) + ":"
                + fillZeroToSize_2(min) + ":"
                + fillZeroToSize_2(sec);
    }

    /**
     * 转换为 yyyy-MM-dd HH:mm 格式
     * @param time 秒级
     */
    public static String formatDateAndTimeByLong(long time) {
        DateFormat mDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());
        return mDateFormat.format(new Date(time * 1000));
    }

    private static String fillZeroToSize_2(long value) {
        if (value < 10) {
            return "0" + value;
        } else {
            return String.valueOf(value);
        }
    }

    /**
     * 获取作业下载时，本地保存的文件名
     * @return 如：homeworkModel:{name="测试.ppt", ext=".ppt", homeworkId="110"} 则返回 "测试（110）.ppt"
     */
    public static String getHomeworkFileName(LPHomeworkModel homeworkModel) {
        if (homeworkModel.getName().length() < homeworkModel.getFext().length()) {
            return "文件名错误：（" + homeworkModel.getHomeworkId() + "）";
        }
        return homeworkModel.getName().substring(0,
                homeworkModel.getName().length() - homeworkModel.getFext().length())
                + "（" + homeworkModel.getHomeworkId() + "）";
    }

    /**
     * 在文件系统中打开目标文件
     * @Warning 如果新增路径，需要在 provider_path 中增加路径声明
     * @param context 上下文
     * @param file 想要查看的文件
     */
    public static void openFileInSystem(Context context, File file) {
        if (file == null || !file.exists()) {
            return;
        }
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        Uri contentUri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            contentUri = HomeworkProvider.getUriForFile(context,
                    context.getApplicationInfo().processName + ".homeworkProvider", file);
        } else {
            contentUri = Uri.fromFile(file);
        }
        intent.setDataAndType(contentUri, FileOptUtil.getMimeType(file.getName()));
        try {
            context.startActivity(Intent.createChooser(intent, "选择浏览工具"));
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static File saveChatImageFile(BitmapDrawable photoView, String fileName) {
        File appDir = new File(Environment.getExternalStorageDirectory(), "bjhl_lp_image");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            photoView.getBitmap().compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
            return file;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 删除文件
     * @param path
     * @return
     */
    public static void deleteFile(String path) {
        File file = new File(path);
        if (file.exists() && file.isFile()) {
            file.delete();
        }
    }
    
    public static boolean isImageFile(String path) {
        if (TextUtils.isEmpty(path)) return false;
        return path.endsWith("png") || path.endsWith("jpg") || path.endsWith("jpeg") || path.endsWith("bmp");
    }

    public static SoundPool playAudio(Context context, int resId) {
        AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        int volumeCurrent = 1;
        if (am != null) {
            volumeCurrent = am.getStreamVolume(AudioManager.STREAM_MUSIC);
        }
        SoundPool soundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
        int soundId = soundPool.load(context, resId, 1);
        int finalVolume = volumeCurrent;
        soundPool.setOnLoadCompleteListener((soundPool1, sampleId, status) -> soundPool.play(soundId, finalVolume, finalVolume, 0, 0, 1));
        return soundPool;
    }

    public static void setRoundCorner(View destView, float radius) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            destView.setOutlineProvider(new ViewOutlineProvider() {
                @Override
                public void getOutline(View view, Outline outline) {
                    if (view.getContext() == null) {
                        return;
                    }
                    outline.setRoundRect(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight(), radius);
                }
            });
            destView.setClipToOutline(true);
        }
    }
    /**
     * 获取应用程序名称
     */
    public static synchronized String getAppName(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
            int labelRes = packageInfo.applicationInfo.labelRes;
            return context.getResources().getString(labelRes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
